﻿using JinYuan.Helper;
using JinYuan.MES.Models;
using JinYuan.Models;
using JinYuan.VirtualDataLibrary;
using Language;
using LargeSquareOne.ViewModel;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LargeSquareOne
{
    public partial class FrmDataMonitor : MultiLanguageForm
    {

        private System.Threading.Timer m_RefreshTimer;
        /// <summary>
        /// 上料条码电池数据显示
        /// </summary>
        private BindingList<AGearEntity> listTA = new BindingList<AGearEntity>();
        /// <summary>
        /// 下料电池数据绑定委托
        /// </summary>
        /// <param name="m"></param>
        private BindingList<BGearEntity> listTB = new BindingList<BGearEntity>();
        /// <summary>
        /// 结构件料盘数据显示
        /// </summary>
        private BindingList<CGearEntity> listTC = new BindingList<CGearEntity>();
        public FrmDataMonitor()
        {
            InitializeComponent();

            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.DoubleBuffer, true);
            this.SetStyle(ControlStyles.ResizeRedraw, true);
            this.SetStyle(ControlStyles.Selectable, true);
            this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            this.SetStyle(ControlStyles.UserPaint, true);

            this.dgvFeedingData.AutoGenerateColumns = false;
            this.dgvFeedingData.DataSource = listTA;
            this.dgvFeedingData.DataError += delegate (object sender, DataGridViewDataErrorEventArgs e) { };
            this.dgvFeedingData.DoubleBufferedDataGirdView(true);

            this.dgvBlankingData.AutoGenerateColumns = false;
            this.dgvBlankingData.DataSource = listTB;
            this.dgvBlankingData.DataError += delegate (object sender, DataGridViewDataErrorEventArgs e) { };
            this.dgvBlankingData.DoubleBufferedDataGirdView(true);

            this.dgvSteelShellData.AutoGenerateColumns = false;
            this.dgvSteelShellData.DataSource = listTC;
            this.dgvSteelShellData.DataError += delegate (object sender, DataGridViewDataErrorEventArgs e) { };
            this.dgvSteelShellData.DoubleBufferedDataGirdView(true);

            this.lVConfigRange.DoubleBufferedListView(true);
            this.FormClosing += (sender, e) =>
            {

            };
        }

        private void FrmDataMonitor_Load(object sender, EventArgs e)
        {

            dgvFeedingData.ClearSelection();
            dgvBlankingData.ClearSelection();

            //表头动态渲染
            this.InitFrmDataMonitor();
        }

        private string CurrentTime
        {
            get { return DateTime.Now.ToString("HH:mm:ss"); }
        }

        /// <summary>
        /// 刷新参数
        /// </summary>
        public void GetLocalParaData()
        {
            try
            {
                if (CommonMethods.paramlists != null)
                {
                    System.Windows.Forms.ListViewItem listItem = null;
                    lVConfigRange.Items.Clear();
                    int j = 0;
                    foreach (var ProductPara in CommonMethods.paramlists)  //遍历list集合
                    {
                        string strRemark = ProductPara.Remark;
                        string strName = ProductPara.ParaName;
                        listItem = new System.Windows.Forms.ListViewItem(CommonMethods.paramlists[j].Remark);
                        listItem.SubItems.Add("0");
                        listItem.SubItems.Add("0");
                        listItem.SubItems.Add("0");
                        lVConfigRange.Items.Add(listItem);
                        lVConfigRange.Items[j].SubItems[1].Text = ProductPara.ParaValueMin;
                        lVConfigRange.Items[j].SubItems[2].Text = ProductPara.ParaValueMax;
                        lVConfigRange.Items[j].SubItems[3].Text = ProductPara.Uint;
                        switch (strName)
                        {
                            //case "intoShellPressure1SettingA07": //入壳压力1
                            //    CommonMethods.parRange.PrePressure1Max = Convert.ToDecimal(ProductPara.ParaValueMax == "" ? "0" : ProductPara.ParaValueMax);
                            //    break;
                            //case "intoShellPressure2SettingA07":  //入壳压力2
                            //    CommonMethods.parRange.PrePressure2Max = Convert.ToDecimal(ProductPara.ParaValueMax == "" ? "0" : ProductPara.ParaValueMax);
                            //    break;
                            //case "intoShellPressure3SettingA07":  //入壳压力3                       
                            //    CommonMethods.parRange.PrePressure3Max = Convert.ToDecimal(ProductPara.ParaValueMax == "" ? "0" : ProductPara.ParaValueMax);
                            //    break;
                            //default:
                            //    break;

                        }
                        j++;
                    }
                }
            }
            catch (Exception ex)
            {

                LogHelper.Instance.WriteEX("获取参数失败".Translated(), ex);
            }
        }


        /// <summary>
        /// 加载MES参数
        /// </summary>
        public async Task<(bool Success, string msg)> GetMesParaDataAsync()
        {
            bool Success = false; // 操作结果
            string Message = "";  // 消息

            try
            {
                bool isChangeParam = false;
                var nowDate = DateTime.Now;

                string filePath = $@"{CommonMethods.strMesLogspath}\参数设定值请求\变更记录\{nowDate.Year}\{nowDate.Month}";
                string fileName = $@"{nowDate.Day}.csv";
                string fileTitle = "时间,机台,MES账户,更改参数名称,更改前参数值,更改后参数值";
                string fileContent = string.Empty;

                DataTable dt = new DataTable();
                dt.Columns.Add("MES账户");
                dt.Columns.Add("更改参数名称");
                dt.Columns.Add("更改前参数值");
                dt.Columns.Add("更改后参数值");

                var (resultData, Mesage) = await CommonMethods.hbgMes.GetParamSetRequestAsync(
                    CommonMethods.mesConfig.DeviceParamChange,
                    CommonMethods.mesConfig.equipNum,
                    CommonMethods.mesConfig.siteCode,
                    CommonMethods.mesConfig.lineCode,
                    CommonMethods.mesConfig.MaterialCode,
                    CommonMethods.mesConfig.mesUserName);

                //var resultData = JsonConvert.DeserializeObject<ParamReturnData>(Data);
                if (!resultData.success)
                {
                    // 获取参数未成功
                    Message = "获取MES参数不成功！";
                    return (Success, Message);
                }

                List<ParamList> NewParamlists = CommonMethods.paramlists;
                for (int i = 0; i < resultData.total; i++)
                {
                    List<RowsItem> rows = resultData.rows;
                    for (int j = 0; j < rows.Count; j++)
                    {
                        var tagList = rows[j].tagList;
                        for (int k = 0; k < NewParamlists.Count; k++)
                        {
                            for (int n = 0; n < rows[j].tagList.Count; n++)
                            {
                                if (NewParamlists[k].ParaName == tagList[n].tagCode)
                                {
                                    string strMin = "0";
                                    if (String.IsNullOrEmpty(tagList[n].minValue.Trim()) || tagList[n].minValue.Trim() == "null")
                                        strMin = "0";
                                    else
                                        strMin = tagList[n].minValue.Trim();
                                    if (NewParamlists[k].ParaValueMin != strMin)
                                    {
                                        fileContent += $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss")},{CommonMethods.mesConfig.equipNum}," +
                                            $"{CommonMethods.mesConfig.mesUserName},{tagList[n].tagDescription}最小值,{NewParamlists[k].ParaValueMin},{strMin}\n";
                                        dt.Rows.Add(CommonMethods.mesConfig.mesUserName, $"{tagList[n].tagDescription}最小值", NewParamlists[k].ParaValueMin, strMin);
                                        NewParamlists[k].ParaValueMin = strMin;
                                        isChangeParam = true;
                                    }
                                    string strMax = "0";
                                    if (String.IsNullOrEmpty(tagList[n].maxValue.Trim()) || tagList[n].maxValue.Trim() == "null")
                                        strMax = "0";
                                    else
                                        strMax = tagList[n].maxValue.Trim();
                                    if (NewParamlists[k].ParaValueMax != tagList[n].maxValue)
                                    {
                                        fileContent += $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss")},{CommonMethods.mesConfig.equipNum}," +
                                            $"{CommonMethods.mesConfig.mesUserName},{tagList[n].tagDescription}最大值,{NewParamlists[k].ParaValueMax},{strMax}\n";
                                        dt.Rows.Add(CommonMethods.mesConfig.mesUserName, $"{tagList[n].tagDescription}最大值", NewParamlists[k].ParaValueMax, strMax);
                                        NewParamlists[k].ParaValueMax = strMax;
                                        isChangeParam = true;
                                    }
                                }
                            }
                        }

                        if (isChangeParam)
                        {
                            CustomMessageBox customMessageBox = new CustomMessageBox(dt, $"当前MES下发参数与设备本地参数不一致，请确认是否使用MES下发参数");
                            if (customMessageBox.ShowDialog() == DialogResult.OK)
                            {
                                // 写csv文件
                                fileContent = fileContent.Substring(0, fileContent.Length - 1);
                                CSVHelper<object>.WriterCSV(filePath, fileName, fileTitle, fileContent);
                                CommonMethods.paramlists = NewParamlists;

                                int res = CommonMethods.db.Delete<ParamList>(it => it.ModelName == CommonMethods.paramlists[0].ModelName);
                                if (res > 0)
                                {
                                    CommonMethods.db.AddReturnBool<ParamList>(CommonMethods.paramlists);
                                }

                                Message = "变更成功并保存";
                                Success = true;
                            }
                            else
                            {
                                Message = "取消变更，采用本地参数配置";
                            }
                            LogHelper.Instance.WriteLog(Message);
                        }
                    }
                }

                Success = true; // 操作成功
                Message = "参数获取成功";
            }
            catch (Exception ex)
            {
                Message = "获取参数失败：" + ex.Message;
                LogHelper.Instance.WriteEX("获取参数失败", ex);
            }

            return (Success, Message);
        }


        #region 显示卷芯上料数据
        /// <summary>
        /// 显示上料
        /// </summary>
        /// <param name="m"></param>
        /// 
        private readonly ConcurrentQueue<List<AGearEntity>> _dataQueue = new ConcurrentQueue<List<AGearEntity>>();
        private volatile bool _isUpdating = false;
        private const int MAX_ROWS = 500;

        public void ShowFeedingData(List<AGearEntity> list)
        {
            if (list == null || list.Count == 0) return;

            try
            {
                _dataQueue.Enqueue(list);
                if (!_isUpdating)
                {
                    ProcessDataQueue();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteEX(ex);
            }
        }

        private void ProcessDataQueue()
        {
            if (_isUpdating) return;

            try
            {
                _isUpdating = true;

                while (_dataQueue.TryDequeue(out var data))
                {
                    UpdateGrid(data);
                }
            }
            finally
            {
                _isUpdating = false;
            }
        }

        private void UpdateGrid(List<AGearEntity> data)
        {
            if (!dgvFeedingData.IsHandleCreated) return;

            try
            {
                dgvFeedingData.BeginInvoke(new Action(() =>
                {
                    try
                    {
                        dgvFeedingData.SuspendLayout();

                        // 检查是否需要清理数据
                        if (listTA.Count > MAX_ROWS)
                        {
                            listTA.Clear();
                            GC.Collect(0, GCCollectionMode.Optimized);
                        }

                        // 添加新数据
                        foreach (var item in data)
                        {
                            listTA.Add(item);
                        }

                        // 更新显示
                        int lastIndex = dgvFeedingData.Rows.Count - 1;
                        if (lastIndex >= 0)
                        {
                            // 更新序号
                            for (int i = 0; i < data.Count && (lastIndex - i) >= 0; i++)
                            {
                                dgvFeedingData.Rows[lastIndex - i].Cells[0].Value = lastIndex + 1 - i;
                            }

                            // 滚动到最新行
                            dgvFeedingData.FirstDisplayedScrollingRowIndex = lastIndex;
                            dgvFeedingData.CurrentCell = dgvFeedingData.Rows[lastIndex].Cells[0];
                        }
                    }
                    finally
                    {
                        dgvFeedingData.ResumeLayout();
                    }
                }));
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteEX(ex);
            }
        }


        #endregion

        #region 显示钢壳上料数据
        /// <summary>
        ///显示钢壳上料数据
        /// </summary>
        /// <param name="m"></param>
        /// 
        #region 显示钢壳上料数据

        private readonly ConcurrentQueue<List<CGearEntity>> _steelShellDataQueue = new ConcurrentQueue<List<CGearEntity>>();
        private volatile bool _isSteelShellUpdating = false;
        private const int MAX_ROWS2 = 50; // 最大行数

        /// <summary>
        /// 显示钢壳上料数据
        /// </summary>
        /// <param name="list"></param>
        public void ShowSteelShellData(List<CGearEntity> list)
        {
            if (list == null || list.Count == 0) return;

            try
            {
                _steelShellDataQueue.Enqueue(list); // 将数据加入队列
                if (!_isSteelShellUpdating)
                {
                    ProcessSteelShellDataQueue(); // 如果当前没有在处理队列，则开始处理
                }
            }
            catch (Exception ex)
            {
                // 记录异常
                LogHelper.Instance.WriteEX(ex);
            }
        }

        /// <summary>
        /// 处理钢壳上料数据队列
        /// </summary>
        private void ProcessSteelShellDataQueue()
        {
            if (_isSteelShellUpdating) return;

            try
            {
                _isSteelShellUpdating = true;

                while (_steelShellDataQueue.TryDequeue(out var data))
                {
                    UpdateSteelShellGrid(data); // 更新 UI
                }
            }
            finally
            {
                _isSteelShellUpdating = false;
            }
        }

        /// <summary>
        /// 更新钢壳上料数据的 UI 显示
        /// </summary>
        /// <param name="data"></param>
        private void UpdateSteelShellGrid(List<CGearEntity> data)
        {
            if (!dgvSteelShellData.IsHandleCreated) return;

            try
            {
                dgvSteelShellData.BeginInvoke(new Action(() =>
                {
                    try
                    {
                        dgvSteelShellData.SuspendLayout();

                        // 检查是否需要清理数据
                        if (listTC.Count >= MAX_ROWS2)
                        {
                            listTC.Clear();
                            GC.Collect(0, GCCollectionMode.Optimized); // 触发垃圾回收
                        }


                        // 添加新数据
                        foreach (var item in data)
                        {
                            listTC.Add(item);
                        }

                        // 设置最新行为活动行 (当前行)
                        int lastIndex = dgvSteelShellData.Rows.Count - 1;
                        if (lastIndex >= 0)
                        {
                            dgvSteelShellData.CurrentCell = dgvSteelShellData.Rows[lastIndex].Cells[0];
                        }
                    }
                    finally
                    {
                        dgvSteelShellData.ResumeLayout();
                    }
                }));
            }
            catch (Exception ex)
            {
                // 记录异常
                LogHelper.Instance.WriteEX(ex);
            }
        }

        #endregion
        #endregion

        #region 显示下料数据
        /// <summary>
        /// 显示下料数据
        /// </summary>
        /// <param name="list"></param>
        public void ShowBankdingData(List<BGearEntity> list)
        {
            try
            {
                if (this.dgvBlankingData.InvokeRequired)
                {
                    this.dgvBlankingData.Invoke(new Action<List<BGearEntity>>(ShowBankdingData), list);
                }
                else
                {
                    if (list != null && list.Count > 0)
                    {
                        foreach (BGearEntity m in list)
                        {
                            listTB.Add(m);
                        }
                        if (listTB.Count >= 500)
                        {
                            listTB.Clear();
                            GC.Collect();
                        }
                    }

                    // 设置最新行为活动行 (当前行)
                    int index = this.dgvBlankingData.Rows.Count - 1;
                    this.dgvBlankingData.CurrentCell = this.dgvBlankingData.Rows[index].Cells[0];
                    for (int i = 0; i < list.Count; i++)
                    {
                        this.dgvBlankingData.Rows[index - i].Cells[0].Value = index + 1 - i;
                    }
                }
            }
            catch (Exception ex)
            {
                //ShowLog("显示上料出现" + ex.Message, 1);
            }
        }

        #endregion

        #region 显示结构件料盘数据
        /// <summary>
        /// 显示结构件料盘数据
        /// </summary>
        /// <param name="list"></param>
        public void ShowMaterialData(List<CGearEntity> list)
        {
            try
            {
                if (this.dgvSteelShellData.InvokeRequired)
                {
                    this.dgvSteelShellData.Invoke(new Action<List<CGearEntity>>(ShowMaterialData), list);
                }
                else
                {
                    if (list != null && list.Count > 0)
                    {
                        foreach (CGearEntity m in list)
                        {
                            listTC.Add(m);
                        }
                        if (listTC.Count >= 500)
                        {
                            listTC.Clear();
                            GC.Collect();
                        }
                    }
                    int index = this.dgvSteelShellData.Rows.Count - 1;

                    // 设置最新行为活动行 (当前行)
                    this.dgvSteelShellData.CurrentCell = this.dgvSteelShellData.Rows[index].Cells[1];
                    this.dgvSteelShellData.BeginEdit(true);

                }
            }
            catch (Exception ex)
            {
                //ShowLog("显示上料出现" + ex.Message, 1);
            }
        }

        #endregion

        private void dgvFeedingData_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //显示序列号
            DataGridViewHelper.DgvRowPostPaint(this.dgvFeedingData, e);
        }

        private void dgvFeedingData_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            //指定列字体颜色
            DataGridViewHelper.DgvRowPrePaint(this.dgvFeedingData, "InResult", sender, e);
        }


        private void dgvBlankingData_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //显示序列号
            DataGridViewHelper.DgvRowPostPaint(this.dgvBlankingData, e);
        }

        private void dgvBlankingData_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            //指定列字体颜色
            DataGridViewHelper.DgvRowPrePaint(this.dgvBlankingData, "OutResult", sender, e);
        }

        #region 减少闪烁
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams parss = base.CreateParams;
                parss.ExStyle |= 0x02000000;
                return parss;
            }
        }


        #endregion

        #region 
        StringFormat sf = new StringFormat { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center };//字体水平位置居左，垂直居中
        private void lVConfigRange_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
        {
            Brush CustomizeBrushColor = new SolidBrush(Color.FromArgb(21, 77, 147));//自定义RGB
            e.Graphics.FillRectangle(CustomizeBrushColor, e.Bounds);   //设置背景颜色
            Font font = new Font("微软雅黑", 12, FontStyle.Bold);      //设置字体大小
            e.Graphics.DrawString(e.Header.Text, font, Brushes.White, e.Bounds, sf); //设置字体颜色
        }

        private void lVConfigRange_DrawItem(object sender, DrawListViewItemEventArgs e)
        {
            e.DrawDefault = true; //采用系统默认方式绘制项
        }

        private void lVConfigRange_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
        {
            e.DrawDefault = true; //采用系统默认方式绘制项
        }

        #endregion

        #region ListView日志记录
        //public void AddDataMonitorLog(int level, string log)
        //{
        //    if (level > 2)
        //    {
        //        level = 2;
        //    }
        //    if (level < 0)
        //    {
        //        level = 0;
        //    }
        //    if (this.lst_Info.InvokeRequired)
        //    {
        //        this.lst_Info.Invoke(new Action<int, string>(AddDataMonitorLog), level, log);
        //    }
        //    else
        //    {
        //        if (this.lst_Info.Items.Count > 1000)
        //        {
        //            this.lst_Info.Items.Clear();
        //        }
        //        System.Windows.Forms.ListViewItem item = new System.Windows.Forms.ListViewItem(" " + CurrentTime, level);
        //        item.SubItems.Add(log);

        //        this.lst_Info.Items.Add(item);

        //        //让最新的日志显示在最下面
        //        this.lst_Info.Items[this.lst_Info.Items.Count - 1].EnsureVisible();


        //    }
        //}
        #endregion

        #region RichTextBox日志记录
        public void AddDataMonitorLog(int type, string info)
        {

            if (this.rtb_Info.InvokeRequired)
            {
                this.rtb_Info.Invoke(new Action<int, string>(AddDataMonitorLog), type, info);

            }
            else
            {

                if (rtb_Info.Lines.Length > 200)  //每当显示的通知数超过200行时，清除前面的150行
                {
                    string[] strlines = new string[rtb_Info.Lines.Length - 150];
                    Array.ConstrainedCopy(rtb_Info.Lines, 50, strlines, 0, strlines.Length);
                    rtb_Info.Lines = strlines;
                    GC.Collect();
                }

                rtb_Info.SelectionStart = rtb_Info.Text.Length;
                rtb_Info.SelectionLength = info.Length;

                switch (type)
                {
                    case 0:
                        rtb_Info.SelectionColor = Color.White;
                        break;
                    case 1:
                        rtb_Info.SelectionColor = Color.DarkOrange;
                        break;
                    case 2:
                        rtb_Info.SelectionColor = Color.Red;
                        break;

                }

                rtb_Info.AppendText(string.Format("时间：{0}-{1}\r\n", DateTime.Now.ToString("HH:mm:ss.fff"), info));

                rtb_Info.SelectionStart = rtb_Info.Text.Length;
                rtb_Info.SelectionLength = info.Length;
                rtb_Info.Focus();
            }
        }
        #endregion

        #region ListBox日志记录
        //public void AddDataMonitorLog(int level, string log)
        //{
        //    Color color = Color.White;
        //    if (level > 2)
        //    {
        //        color= Color.Red;
        //        level = 2;
        //    }
        //    if (level < 0)
        //    {
        //        color = Color.White;
        //        level = 0;
        //    }
        //    if (this.lis_Info.InvokeRequired)
        //    {
        //        this.lis_Info.Invoke(new Action<int, string>(AddDataMonitorLog), level, log);

        //    }
        //    else
        //    {

        //        this.lis_Info.AddLog(log, color);
        //        this.lis_Info.SelectedIndex = this.lis_Info.Items.Count - 1;
        //        this.lis_Info.SelectedIndex = -1;

        //        //System.Windows.Forms.ListViewItem item = new System.Windows.Forms.ListViewItem(" " + CurrentTime, level);
        //        //item.SubItems.Add(log);

        //        //this.rtb_Info.Items.Add(item);

        //        ////让最新的日志显示在最下面
        //        //this.rtb_Info.Items[this.lst_Info.Items.Count - 1].EnsureVisible();
        //    }
        //}
        #endregion
    }

}
